package com.example;
//ctrl + alt + o 导包

import lombok.Data;
import java.util.Random;

//ThreadLocal类，实现了线程内部共享数据，线程间数据独立，比05节视频中的更加简化方便
public class ThreadLocalTest {
    //一个ThreadLocal代表一个变量，故其中只能放一个数据
    private static ThreadLocal<Integer> x = new ThreadLocal<>();
    private static ThreadLocal<MyThreadScopeData> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            int data = new Random().nextInt();
                            System.out.println(Thread.currentThread().getName() + "has put data:" + data);
                            //存到当前线程
                            x.set(data);
                            //MyThreadScopeData myData = new MyThreadScopeData();
                            MyThreadScopeData myData = MyThreadScopeData.getInstance();
                            myData.setName("name" + data);
                            myData.setAge(data);
                            threadLocal.set(myData);
                            new A().get();
                            new B().get();
                        }
                    }
            ).start();
        }
    }

    static class A {
        public void get() {
            int data = x.get();
            System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data);

            MyThreadScopeData myData = threadLocal.get();
            System.out.println("A from" + Thread.currentThread().getName() + "get myData:" + myData.getName() + "," + myData.getAge());

        }
    }

    static class B {
        public void get() {
            int data = x.get();
            System.out.println("B from" + Thread.currentThread().getName() + "get data:" + data);
            MyThreadScopeData myData = threadLocal.get();
            System.out.println("B from" + Thread.currentThread().getName() + "get myData:" + myData.getName() + "," + myData.getAge());
        }
    }
}

@Data
class MyThreadScopeData {
    //public MyThreadScopeData() {
    private MyThreadScopeData() {
    }

    //饱汉模式
    //public static MyThreadScopeData getInstance() {
    //    return instance;
    //}
    //
    //private static MyThreadScopeData instance = new MyThreadScopeData();

    //饥汉模式，要加互斥synchronized
    public static synchronized MyThreadScopeData getInstance() {
        if (instance == null) {
            //多个线程同时进入可能会产生多个实例，所以要加synchronized
            instance = new MyThreadScopeData();
        }
        return instance;
    }

    private static MyThreadScopeData instance = null;

    private String name;
    private int age;
}
